<template>
  <!--面包屑导航-->
  <Breadcrumb>
    <template #firstTitle>
      <span>商品管理</span>
    </template>
    <template #secondTitle>
      <span>{{ isEidt ? "编辑商品" : "添加商品" }}</span>
    </template>
  </Breadcrumb>

  <!--卡片视图-->
  <el-card>
    <el-page-header :content="isEidt ? '编辑商品信息' : '添加商品信息'" @back="goBack" />

    <!--步骤条-->
    <el-steps :space="300" align-center :active="activeIndex - 0" finish-status="success">
      <el-step title="基本信息"></el-step>
      <el-step title="商品参数"></el-step>
      <el-step title="商品属性"></el-step>
      <el-step title="商品图片"></el-step>
      <el-step title="商品内容"></el-step>
      <el-step title="完成"></el-step>
    </el-steps>

    <!-- tab标签 -->
    <el-form
      status-icon
      ref="form"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      label-position="top"
      @submit.prevent="handleSubmit"
    >
      <el-tabs
        v-model="activeIndex"
        tab-position="left"
        :before-leave="beforeTabLeave"
        @tab-click="tabClicked"
      >
        <!-- 基本信息 -->
        <el-tab-pane label="基本信息" name="0">
          <el-form-item label="商品名称" prop="goods_name">
            <el-input v-model="formData.goods_name" />
          </el-form-item>
          <el-form-item label="商品价格" prop="goods_price">
            <el-input-number v-model="formData.goods_price" :min="1" />
          </el-form-item>
          <el-form-item label="商品重量" prop="goods_weight">
            <el-input-number v-model="formData.goods_weight" :min="1" />
          </el-form-item>
          <el-form-item label="商品数量" prop="goods_number">
            <el-input-number v-model="formData.goods_number" :min="1" />
          </el-form-item>
          <el-form-item label="商品分类" prop="goods_cat">
            <el-cascader
              v-model="formData.goods_cat"
              :options="cateList"
              :props="cateProps"
              @change="cateChange"
              clearable
              style="width: 50%"
            ></el-cascader>
          </el-form-item>
        </el-tab-pane>

        <!-- 商品参数 -->
        <el-tab-pane label="商品参数" name="1">
          <!--渲染表单的item项-->
          <el-form-item
            v-for="item in manyTableData"
            :key="item.attr_id"
            :label="item.attr_name"
          >
            <!--复选框组-->
            <el-checkbox-group v-model="item.attr_vals">
              <el-checkbox
                border
                v-for="(item2, index2) in item.attr_vals"
                :key="index2 + item2"
                :label="item2"
              ></el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-tab-pane>

        <!-- 商品属性 -->
        <el-tab-pane label="商品属性" name="2">
          <el-form-item
            v-for="item in onlyTableData"
            :key="item.attr_id"
            :label="item.attr_name"
          >
            <el-input v-model="item.attr_vals" />
          </el-form-item>
        </el-tab-pane>

        <!-- 商品图片 -->
        <el-tab-pane label="商品图片" name="3">
          <el-upload
            v-model:file-list="fileList"
            :action="uploadURL"
            :headers="headersObj"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            list-type="picture"
            accept="image/png, image/jpeg, image/jpg"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                图片格式为 image/png, image/jpeg, image/jpg,
              </div>
            </template>
          </el-upload>
        </el-tab-pane>

        <!-- 商品内容 -->
        <el-tab-pane label="商品内容" name="4">
          <!--富文本编辑器组件-->
          <AppWangeEditor ref="myEditor" v-model="formData.goods_introduce" />
          <!--添加商品按钮-->
          <el-button
            type="primary"
            class="btn-submit"
            :loading="loading"
            native-type="submit"
            >{{ isEidt ? "编辑" : "添加" }}</el-button
          >
        </el-tab-pane>
      </el-tabs>
    </el-form>
  </el-card>

  <!--图片预览-->
  <el-dialog v-model="previewVisible" width="50%">
    <img w-full :src="previewPath" alt="" class="preview-img" />
  </el-dialog>
</template>

<script setup>
import _ from "lodash";
import { computed, nextTick, onMounted, ref, reactive } from "vue-demi";
import { useRouter, useRoute } from "vue-router";
import { getCategories } from "@/api/categories.js";
import { getCategoriesParam } from "@/api/params.js";
import { getGoodsById, addGoods, editGoods } from "@/api/goods.js";
import { ElMessage } from "element-plus";
import { useStore } from "@/store";

const store = useStore();
const router = useRouter(); // router 实例
const route = useRoute(); // 当前路由地址
const activeIndex = ref("0");
const form = ref(null);
const myEditor = ref(null);
const loading = ref(false);
const formData = ref({
  goods_name: "", //商品名称
  goods_price: 0, //商品价格
  goods_weight: 0, //商品重量
  goods_number: 0, //商品数量
  goods_cat: [], //商品分类
  pics: [], //商品图片
  goods_introduce: "", //商品内容描述
  attrs: [],
});
const formRules = {
  goods_name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  goods_price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
  goods_weight: [{ required: true, message: "请输入商品重量", trigger: "blur" }],
  goods_number: [{ required: true, message: "请输入商品数量", trigger: "blur" }],
  goods_cat: [{ required: true, message: "请选择商品分类", trigger: "change" }],
};
const cateList = ref([]); //商品分类列表
const cateProps = {
  //指定级联选择器的配置对象
  expandTrigger: "hover",
  value: "cat_id",
  label: "cat_name",
  children: "children",
};
const manyTableData = ref([]); //商品参数
const onlyTableData = ref([]); //商品属性
// 当前选中的商品分类ID(计算属性)
const cateId = computed(() => {
  if (formData.value.goods_cat.length === 3) {
    return formData.value.goods_cat[2];
  } else {
    return "";
  }
});
const fileList = ref([]);
let api = '', envMode = import.meta.env.MODE
if (envMode === "development") {
  api = import.meta.env.VITE_APP_DEVLOPMENT_API_URL
} else {
  api = import.meta.env.VITE_APP_PRODUCTION_API_URL
}
const uploadURL = api + "/upload"; //上传图片的URL地址
const headersObj = {
  //图片上传组件的headers请求头
  Authorization: store.state.user.token,
};
const previewPath = ref(""); //预览图片路径
const previewVisible = ref(false); //预览图片显示/隐藏
const isEidt = ref(false); // 是否为编辑
const goodsId = route.params.id || null;

onMounted(() => {
  if (goodsId) {
    isEidt.value = true;
    loadDataInfo();
  }
  getCateList();
});

// 编辑页面时请求数据
const loadDataInfo = async () => {
  const data = await getGoodsById(goodsId);

  data.goods_cat = data.goods_cat.split(",").map(Number);
  formData.value = { ...data };

  data.attrs.forEach((item) => {
    if (item.attr_write === "list") {
      manyTableData.value.push(item);
    } else {
      onlyTableData.value.push(item);
    }
  });
  manyTableData.value.forEach((item) => {
    item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
  });
  // 商品图片
  fileList.value = data.pics.map((item) => {
    return {
      name: item.pics_id,
      url: item.pics_big_url,
    };
  });
};

// 获取商品分类
const getCateList = async () => {
  const data = await getCategories();
  cateList.value = data;
};

// tab切换标签之前的钩子，若返回 false 或者返回 Promise 且被 reject，则阻止切换。
const beforeTabLeave = (activeName, oldActiveName) => {
  if (oldActiveName === "0" && formData.value.goods_cat.length !== 3) {
    ElMessage.error(`请先选择商品分类！`);
    return false;
  }
};

// tab 被选中时触发
const tabClicked = () => {
  nextTick(() => {
    if (activeIndex.value == "1") {
      //获取商品参数
      getParamsData("many");
    } else if (activeIndex.value == "2") {
      //获取商品属性
      getParamsData("only");
    }
  });
};

// 获取参数列表数据
const getParamsData = async (type) => {
  // 根据所选分类ID和当前所处的面板获取对应的参数
  const data = await getCategoriesParam(cateId.value, type);

  if (type === "many") {
    data.forEach((item) => {
      item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
    });
    manyTableData.value = data;
  } else {
    onlyTableData.value = data;
  }
};

// 选择商品分类
const cateChange = () => {
  if (formData.value.goods_cat.length !== 3) {
    formData.value.goods_cat = [];
    return;
  }
  // getParamsData();
};

// 处理图片预览效果
const handlePreview = (file) => {
  previewPath.value = file.response.data.url;
  previewVisible.value = true;
};

// 处理图片移除操作
const handleRemove = (file, fileList) => {
  // 1.获取将要删除的图片临时路径
  const filePath = file.response.data.tmp_path;

  // 2.从pics数组中找到这个图片对应的索引值
  const index = formData.value.pics.findIndex((x) => x.pic === filePath);

  // 3.调用数组的splice方法，把图片信息对象从pics数组中移除
  formData.value.pics.splice(index, 1);
};

// 文件上传成功时的钩子
const handleSuccess = (response) => {
  // 1.拼接得到一个图片信息对象
  const picInfo = {
    pic: response.data.tmp_path,
  };
  // 2.将图片信息对象push到pics数组中
  formData.value.pics.push(picInfo);
};

const handleSubmit = async () => {
  // const valid = form.value.validate();
  // if (!valid) {
  //   ElMessage.error('请填写必要的表单项');
  //   return;
  // }

  // 执行添加的业务逻辑（先深拷贝，再调整数据结构）
  // 处理动态参数(商品参数、商品属性)
  manyTableData.value.forEach((item) => {
    const newInfo = {
      attr_id: item.attr_id,
      attr_value: item.attr_vals.join(" "),
    };
    formData.value.attrs.push(newInfo);
  });
  // 处理静态属性
  onlyTableData.value.forEach((item) => {
    const newInfo = {
      attr_id: item.attr_id,
      attr_value: item.attr_vals,
    };
    formData.value.attrs.push(newInfo);
  });

  //深拷贝
  const form = _.cloneDeep(formData.value);
  form.goods_cat = form.goods_cat.join(",");

  loading.value = true;
  if (goodsId) {
    // 编辑商品
    await editGoods(goodsId, form).finally(() => {
      loading.value = false;
    });
    ElMessage.success("编辑成功");
  } else {
    // 添加商品
    await addGoods(form).finally(() => {
      loading.value = false;
    });
    ElMessage.success("添加成功");
  }

  router.push("/goods");
};

const goBack = () => {
  router.push("/goods");
};
</script>

<style lang="scss" scoped>
.el-page-header {
  padding: 10px 0 !important;
}
.el-steps {
  margin-bottom: 30px;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.preview-img {
  width: 100%;
}
.btn-submit {
  margin-top: 15px;
}
</style>
